package cn.edu.tju.elm.service;

import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.model.BankCard;
import cn.edu.tju.elm.model.BankCardTransaction;
import cn.edu.tju.elm.repository.BankCardRepository;
import cn.edu.tju.elm.repository.BankCardTransactionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 银行卡业务逻辑层
 */
@Service
@Transactional
public class BankCardService {

    @Autowired
    private BankCardRepository bankCardRepository;

    @Autowired
    private BankCardTransactionRepository transactionRepository;

    @Autowired
    private UserService userService;

    /**
     * 绑定银行卡
     * @param bankCard 银行卡信息
     * @return 绑定后的银行卡
     */
    public BankCard bindBankCard(BankCard bankCard) {
        // 获取当前用户
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            throw new IllegalArgumentException("用户未认证");
        }

        // 检查银行卡号是否已存在
        if (bankCardRepository.existsByCardNumber(bankCard.getCardNumber())) {
            throw new IllegalArgumentException("银行卡号已存在");
        }

        // 检查用户银行卡数量限制（最多5张）
        long cardCount = bankCardRepository.countByUserId(currentUser.getId());
        if (cardCount >= 5) {
            throw new IllegalArgumentException("银行卡数量已达上限（5张）");
        }

        // 设置用户信息
        bankCard.setUser(currentUser);
        bankCard.setBindTime(LocalDateTime.now());
        bankCard.setStatus(1); // 正常状态

        // 如果是第一张银行卡，设为默认
        if (cardCount == 0) {
            bankCard.setIsDefault(true);
        }

        // 加密银行卡号（这里简化处理，实际应该使用加密算法）
        String encryptedCardNumber = encryptCardNumber(bankCard.getCardNumber());
        bankCard.setCardNumber(encryptedCardNumber);

        return bankCardRepository.save(bankCard);
    }

    /**
     * 解绑银行卡
     * @param cardId 银行卡ID
     * @return 是否解绑成功
     */
    public boolean unbindBankCard(Long cardId) {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            throw new IllegalArgumentException("用户未认证");
        }

        Optional<BankCard> cardOpt = bankCardRepository.findById(cardId);
        if (cardOpt.isPresent()) {
            BankCard bankCard = cardOpt.get();
            
            // 检查是否为当前用户的银行卡
            if (!bankCard.getUser().getId().equals(currentUser.getId())) {
                throw new IllegalArgumentException("无权限操作此银行卡");
            }

            // 检查银行卡状态
            if (bankCard.getStatus() != 1) {
                throw new IllegalArgumentException("银行卡状态异常，无法解绑");
            }

            // 检查是否有未完成的交易
            List<BankCardTransaction> pendingTransactions = transactionRepository
                    .findByBankCardIdAndStatus(cardId, 3); // 处理中状态
            if (!pendingTransactions.isEmpty()) {
                throw new IllegalArgumentException("存在未完成的交易，无法解绑");
            }

            // 如果是默认银行卡，需要设置其他银行卡为默认
            if (bankCard.getIsDefault()) {
                List<BankCard> otherCards = bankCardRepository.findByUserId(currentUser.getId());
                otherCards.remove(bankCard);
                if (!otherCards.isEmpty()) {
                    otherCards.get(0).setIsDefault(true);
                    bankCardRepository.save(otherCards.get(0));
                }
            }

            // 删除银行卡
            bankCardRepository.delete(bankCard);
            return true;
        }
        return false;
    }

    /**
     * 获取用户银行卡列表
     * @param userId 用户ID
     * @return 银行卡列表
     */
    @Transactional(readOnly = true)
    public List<BankCard> getUserBankCards(Long userId) {
        return bankCardRepository.findByUserId(userId);
    }

    /**
     * 获取当前用户银行卡列表
     * @return 银行卡列表
     */
    @Transactional(readOnly = true)
    public List<BankCard> getCurrentUserBankCards() {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            throw new IllegalArgumentException("用户未认证");
        }
        return bankCardRepository.findByUserId(currentUser.getId());
    }

    /**
     * 根据ID获取银行卡
     * @param cardId 银行卡ID
     * @return 银行卡信息
     */
    @Transactional(readOnly = true)
    public Optional<BankCard> getBankCardById(Long cardId) {
        return bankCardRepository.findById(cardId);
    }

    /**
     * 设置默认银行卡
     * @param cardId 银行卡ID
     * @return 是否设置成功
     */
    public boolean setDefaultBankCard(Long cardId) {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            throw new IllegalArgumentException("用户未认证");
        }

        Optional<BankCard> cardOpt = bankCardRepository.findById(cardId);
        if (cardOpt.isPresent()) {
            BankCard bankCard = cardOpt.get();
            
            // 检查是否为当前用户的银行卡
            if (!bankCard.getUser().getId().equals(currentUser.getId())) {
                throw new IllegalArgumentException("无权限操作此银行卡");
            }

            // 检查银行卡状态
            if (bankCard.getStatus() != 1) {
                throw new IllegalArgumentException("银行卡状态异常");
            }

            // 取消其他银行卡的默认状态
            List<BankCard> userCards = bankCardRepository.findByUserId(currentUser.getId());
            for (BankCard card : userCards) {
                if (card.getIsDefault()) {
                    card.setIsDefault(false);
                    bankCardRepository.save(card);
                }
            }

            // 设置当前银行卡为默认
            bankCard.setIsDefault(true);
            bankCardRepository.save(bankCard);
            return true;
        }
        return false;
    }

    /**
     * 获取用户默认银行卡
     * @param userId 用户ID
     * @return 默认银行卡
     */
    @Transactional(readOnly = true)
    public Optional<BankCard> getDefaultBankCard(Long userId) {
        return bankCardRepository.findByUserIdAndIsDefaultTrue(userId);
    }

    /**
     * 银行卡充值
     * @param cardId 银行卡ID
     * @param amount 充值金额
     * @return 充值后的银行卡
     */
    public BankCard rechargeBankCard(Long cardId, BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("充值金额必须大于0");
        }

        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            throw new IllegalArgumentException("用户未认证");
        }

        Optional<BankCard> cardOpt = bankCardRepository.findById(cardId);
        if (cardOpt.isPresent()) {
            BankCard bankCard = cardOpt.get();
            
            // 检查权限
            if (!bankCard.getUser().getId().equals(currentUser.getId())) {
                throw new IllegalArgumentException("无权限操作此银行卡");
            }

            // 检查银行卡状态
            if (bankCard.getStatus() != 1) {
                throw new IllegalArgumentException("银行卡状态异常");
            }

            // 只有储蓄卡可以充值
            if (bankCard.getCardType() != 1) {
                throw new IllegalArgumentException("只有储蓄卡可以充值");
            }

            // 记录交易前余额
            BigDecimal balanceBefore = bankCard.getBalance();
            BigDecimal balanceAfter = balanceBefore.add(amount);

            // 更新余额
            bankCard.setBalance(balanceAfter);
            bankCard.setLastUsedTime(LocalDateTime.now());

            // 创建交易记录
            BankCardTransaction transaction = new BankCardTransaction();
            transaction.setBankCard(bankCard);
            transaction.setUser(currentUser);
            transaction.setTransactionType(1); // 充值
            transaction.setAmount(amount);
            transaction.setBalanceBefore(balanceBefore);
            transaction.setBalanceAfter(balanceAfter);
            transaction.setStatus(1); // 成功
            transaction.setTransactionNo(generateTransactionNo());
            transaction.setDescription("银行卡充值");
            transaction.setTransactionTime(LocalDateTime.now());

            transactionRepository.save(transaction);
            return bankCardRepository.save(bankCard);
        }
        throw new IllegalArgumentException("银行卡不存在");
    }

    /**
     * 银行卡支付
     * @param cardId 银行卡ID
     * @param amount 支付金额
     * @param orderId 订单ID
     * @return 支付结果
     */
    public boolean payWithBankCard(Long cardId, BigDecimal amount, Long orderId) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("支付金额必须大于0");
        }

        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            throw new IllegalArgumentException("用户未认证");
        }

        Optional<BankCard> cardOpt = bankCardRepository.findById(cardId);
        if (cardOpt.isPresent()) {
            BankCard bankCard = cardOpt.get();
            
            // 检查权限
            if (!bankCard.getUser().getId().equals(currentUser.getId())) {
                throw new IllegalArgumentException("无权限操作此银行卡");
            }

            // 检查银行卡状态
            if (bankCard.getStatus() != 1) {
                throw new IllegalArgumentException("银行卡状态异常");
            }

            // 检查余额是否足够
            BigDecimal availableAmount = bankCard.getAvailableAmount();
            if (availableAmount.compareTo(amount) < 0) {
                throw new IllegalArgumentException("余额不足");
            }

            // 记录交易前余额
            BigDecimal balanceBefore = bankCard.getCardType() == 1 ? bankCard.getBalance() : bankCard.getUsedCredit();
            BigDecimal balanceAfter;

            // 更新余额
            if (bankCard.getCardType() == 1) { // 储蓄卡
                balanceAfter = bankCard.getBalance().subtract(amount);
                bankCard.setBalance(balanceAfter);
            } else { // 信用卡
                balanceAfter = bankCard.getUsedCredit().add(amount);
                bankCard.setUsedCredit(balanceAfter);
            }

            bankCard.setLastUsedTime(LocalDateTime.now());

            // 创建交易记录
            BankCardTransaction transaction = new BankCardTransaction();
            transaction.setBankCard(bankCard);
            transaction.setUser(currentUser);
            transaction.setTransactionType(2); // 消费
            transaction.setAmount(amount);
            transaction.setBalanceBefore(balanceBefore);
            transaction.setBalanceAfter(balanceAfter);
            transaction.setStatus(1); // 成功
            transaction.setOrderId(orderId);
            transaction.setTransactionNo(generateTransactionNo());
            transaction.setDescription("订单支付");
            transaction.setTransactionTime(LocalDateTime.now());

            transactionRepository.save(transaction);
            bankCardRepository.save(bankCard);
            return true;
        }
        throw new IllegalArgumentException("银行卡不存在");
    }

    /**
     * 获取银行卡交易记录
     * @param cardId 银行卡ID
     * @return 交易记录列表
     */
    @Transactional(readOnly = true)
    public List<BankCardTransaction> getBankCardTransactions(Long cardId) {
        return transactionRepository.findByBankCardId(cardId);
    }

    /**
     * 获取用户交易记录
     * @param userId 用户ID
     * @return 交易记录列表
     */
    @Transactional(readOnly = true)
    public List<BankCardTransaction> getUserTransactions(Long userId) {
        return transactionRepository.findByUserId(userId);
    }

    /**
     * 更新银行卡信息
     * @param bankCard 银行卡信息
     * @return 更新后的银行卡
     */
    public BankCard updateBankCard(BankCard bankCard) {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            throw new IllegalArgumentException("用户未认证");
        }

        Optional<BankCard> existingCardOpt = bankCardRepository.findById(bankCard.getId());
        if (existingCardOpt.isPresent()) {
            BankCard existingCard = existingCardOpt.get();
            
            // 检查权限
            if (!existingCard.getUser().getId().equals(currentUser.getId())) {
                throw new IllegalArgumentException("无权限操作此银行卡");
            }

            // 更新允许修改的字段
            if (bankCard.getPhone() != null) {
                existingCard.setPhone(bankCard.getPhone());
            }
            if (bankCard.getRemark() != null) {
                existingCard.setRemark(bankCard.getRemark());
            }

            return bankCardRepository.save(existingCard);
        }
        throw new IllegalArgumentException("银行卡不存在");
    }

    /**
     * 加密银行卡号（简化实现）
     * @param cardNumber 原始银行卡号
     * @return 加密后的银行卡号
     */
    private String encryptCardNumber(String cardNumber) {
        // 这里应该使用真正的加密算法，如AES
        // 为了演示，这里只是简单处理
        if (cardNumber.length() > 4) {
            return "****" + cardNumber.substring(cardNumber.length() - 4);
        }
        return cardNumber;
    }

    /**
     * 生成交易流水号
     * @return 交易流水号
     */
    private String generateTransactionNo() {
        return "TXN" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }
}

